package com.weilele.base.library.net

import kotlinx.coroutines.*
import retrofit2.*
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException


/**
 * 会抛出异常
 */
suspend fun <T : Any> Call<T>.awaitCall(): T {
    return suspendCancellableCoroutine { continuation ->
        continuation.invokeOnCancellation {
            cancel()
        }
        enqueue(object : Retrofit2Call<T>() {
            override fun onSuccess(result: T) {
                continuation.resume(result)
            }

            override fun onError(t: Throwable, errorCode: Int?) {
                continuation.resumeWithException(t)
            }
        })
    }
}

/**
 * retrofit请求回调
 *
 */
abstract class Retrofit2Call<T> : Callback<T> {

    override fun onFailure(call: Call<T>, t: Throwable) {
        onError(t, null)
    }

    override fun onResponse(call: Call<T>, response: Response<T>) {
        if (response.isSuccessful) {
            val body = response.body()
            if (body == null) {
                val invocation = call.request().tag(Invocation::class.java)!!
                val method = invocation.method()
                val e = KotlinNullPointerException(
                    "Response from " +
                            method.declaringClass.name +
                            '.' +
                            method.name +
                            " was null but response body type was declared as non-null"
                )
                onError(e, response.code())
            } else {
                onSuccess(body)
            }
        } else {
            onError(HttpException(response), response.code())
        }
    }

    //请求成功
    abstract fun onSuccess(result: T)

    //请求失败
    abstract fun onError(t: Throwable, errorCode: Int?)
}



